
package com.cgmnx.admin.common.util;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 *
 */
public final class WebUtils {

    private static final String HEADER_X_REAL_IP = "X-Real-IP";

    public static String resolveBindingResult(BindingResult result) {
        return StringUtil.joiner_enter.join(Lists.transform(result.getFieldErrors(), new Function<FieldError, String>() {
            @Override
            public String apply(FieldError input) {
                return input.getDefaultMessage();
            }
        }));
    }

    /**
     * 获取客户端IP
     *
     * @param request
     * @return
     */
    public static String getRealIP(HttpServletRequest request) {
        String ip = request.getHeader(HEADER_X_REAL_IP);
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");// 这是一个可以伪造的头
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        }
        // 最后一个为RemoteAddr
        int pos = ip.lastIndexOf(',');
        if (pos >= 0) {
            ip = ip.substring(pos);
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }

    /**
     * 从<code>ServletRequest</code>中获取URI中应用上下文部分以后的<code>pathInfo</code>。
     *
     * @param request <code>ServletRequest</code>实例
     * @return 不包含应用上下文的路径。参数request为null时返回null，应用上下文后无内容时返回空字符串。
     */
    public static String getPathInfo(ServletRequest request) {
        if (request == null) {
            return null;
        }
        //取得pathInfo
        return ((HttpServletRequest) request).getRequestURI().replaceFirst(
                ((HttpServletRequest) request).getContextPath(), "");
    }


}